<template>
    <div class="page-wrap page-wrap-ql">
        <div class="page-cont">
            <h-section title="规划版本/发起评审">
                <div>
                    <a-steps direction="vertical">
                        <a-step title="预设版本，圈定评审需求列表">
                            <template #description>
                                <a-form layout="inline" ref="formRef">
                                    <a-row>
                                        <a-col :span="24">
                                            <a-form-item label="版本号">
                                                <a-row>
                                                    <a-col :span="8">
                                                        <div style="width: 100%">
                                                            <h-search-select-cell
                                                                type="version"
                                                                label="versionName"
                                                                :searchQuery="versionSearchQuery"
                                                                @success="handleSelectChange"
                                                            >
                                                                <template #label="{ record }">
                                                                    {{ record.versionName }}—{{ record.versionNumber }}
                                                                </template>
                                                            </h-search-select-cell>
                                                        </div>
                                                    </a-col>
                                                    <a-col :span="24">
                                                        <div style="width: 100%; margin-top: 16px">
                                                            <require-transfer ref="requireTransferRef" />
                                                        </div>
                                                    </a-col>
                                                </a-row>
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                </a-form>
                            </template>
                        </a-step>
                        <a-step title="上传评审相关文件，例如需求文档等">
                            <template #description>
                                <a-form layout="inline" ref="formRef">
                                    <a-row>
                                        <a-col :span="12">
                                            <a-form-item label="需求文档">
                                                <upload-cell
                                                    :span="24"
                                                    :fileParams="{ connectType: '需求文档', type: 1 }"
                                                    @valueChange="fileChange"
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                </a-form>
                            </template>
                        </a-step>
                    </a-steps>
                    <flexbox justify="flex-end" class="btn-group">
                        <a-button type="primary" @click="handleOk(1)">发起评审</a-button>
                        <a-button @click="handleOk(2)">保存版本</a-button>
                    </flexbox>
                </div>
            </h-section>
        </div>
    </div>
</template>

<script lang="ts">
import { message } from 'ant-design-vue';
import UploadCell from '@/components/UploadCell/index.vue';
import RequireTransfer from './components/RequireTransfer.vue';
import HSearchSelectCell from '@/components/HSearchSelect/HSearchSelectCell.vue';
import api from '@/api';
import store from '@/store';
import { useRouter } from 'vue-router';
import { defineComponent, ref, unref, reactive, toRefs, computed } from 'vue';
export default defineComponent({
    name: 'StartProccess',
    components: {
        UploadCell,
        RequireTransfer,
        HSearchSelectCell
    },
    setup() {
        const router = useRouter();
        const requireTransferRef = ref<any>();
        const state = reactive<any>({
            list: [],
            current: 1,
            version: '',
            detailData: {},
            files: []
        });
        const versionSearchQuery = computed(() => {
            const checkedList = store.state.proRequire.checkedList;
            if (checkedList.length) {
                return {
                    system: checkedList[0].requireSystem
                };
            } else {
                return {};
            }
        });
        // 通用选择回调
        const handleSelectChange = (val) => {
            getDetailData(val.id);
            state.version = val.id;
        };
        // 详情，并获取版本号下的所有需求列表
        const getDetailData = async (id: string) => {
            const query = {
                id
            };
            const { success, moule, errorMsg } = await api.versionModel.findById(query);
            if (success) {
                state.detailData = moule;
                const targetList = moule.pmpProductRequires ? [...moule.pmpProductRequires] : [];
                init(targetList);
            } else {
                message.error(errorMsg);
            }
        };
        // 初始化数据
        const init = (list: any[]) => {
            unref(requireTransferRef).init(list);
        };
        const handleValidate = (type: number) => {
            const checkedList = unref(requireTransferRef).checkedLeftData;
            let errorMsg = '';
            let success = true;
            // 必须选择文件和选择版本号且版本号下有产品需求才能才能发起评审
            if (type === 1) {
                if (!state.version) {
                    success = false;
                    errorMsg = '版本不能为空';
                } else if (!checkedList.length) {
                    success = false;
                    errorMsg = '版本下产品需求不能为空';
                } else {
                    const fileList = state.files.length ? state.files.filter(({ status }) => status !== 'delete') : [];
                    if (!fileList.length) {
                        success = false;
                        errorMsg = '文件不能为空';
                    }
                }
            }
            // 必须选择版本号，且版本号下有产品需求才能保存版本
            if (type === 2) {
                if (!state.version) {
                    success = false;
                    errorMsg = '版本不能为空';
                } else if (!checkedList.length) {
                    success = false;
                    errorMsg = '版本下产品需求不能为空';
                }
            }
            return { success, errorMsg };
        };
        const handleOk = (type: number) => {
            const { success, errorMsg } = handleValidate(type);
            //发起需求
            if (success) {
                if (type === 1) {
                    handleBatch().then((res) => {
                        if (res) {
                            handleStartProcess();
                        }
                    });
                }
                // 保存版本
                if (type === 2) {
                    handleBatch().then((res) => {
                        if (res) {
                            handleSave();
                        }
                    });
                }
            } else {
                message.error(errorMsg);
            }
        };
        // 版本绑定需求
        const handleBatch = async () => {
            const list: any[] = [];
            //版本下的所有需求列表
            const requireList = state.detailData.pmpProductRequires || [];
            //左侧选中的列表
            const checkedList = unref(requireTransferRef).checkedLeftData;
            // 将新增的先添加
            let addList: any[] = [];
            addList = requireList.length ? checkedList.filter((item) => !requireList.find((elem) => elem.id === item.id)) : checkedList;
            addList.forEach((item) => {
                const { id, versionName, versionNumber } = state.detailData;
                list.push({
                    productRequireId: item.id,
                    relateVersionId: id,
                    relateVersionName: versionName,
                    relateVersionNumber: versionNumber,
                    status: 'add'
                });
            });
            // 查找删除的项
            if (requireList.length) {
                requireList.forEach((item) => {
                    const { id, versionName, versionNumber } = state.detailData;
                    list.push({
                        productRequireId: item.id,
                        relateVersionId: id,
                        relateVersionName: versionName,
                        relateVersionNumber: versionNumber,
                        status: checkedList.find((elem) => elem.id === item.id) ? '' : 'delete'
                    });
                });
            }
            const { success, errorMsg } = await api.productRequireModel.batchDeal(list);
            if (success) {
                message.success('操作成功');
            } else {
                message.error(errorMsg);
            }
            return success;
        };
        // 发起评审
        const handleStartProcess = async () => {
            const query = {
                ...state.detailData,
                files: [...state.files],
                pmpProductRequires: null
            };
            const { success, errorMsg } = await api.productProcessModel.startProcess(query);
            if (success) {
                router.push({
                    path: '/version/versionList'
                });
            } else {
                message.error(errorMsg);
            }
        };
        // 保存版本
        const handleSave = async () => {
            const query = {
                id: state.detailData.id,
                files: [...state.files]
            };
            const { success, errorMsg } = await api.versionModel.save(query);
            if (success) {
                message.success('保存成功');
            } else {
                message.error(errorMsg);
            }
        };
        // 监听文件删除等操作
        const fileChange = (fileList: any[]) => {
            state.files = [...fileList];
        };
        return {
            requireTransferRef,
            ...toRefs(state),
            versionSearchQuery,
            handleSelectChange,
            handleOk,
            fileChange
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        min-height: 516px;
        background: #fff;
        .btn-group {
            margin: 24px 0;
            .ant-btn + .ant-btn {
                margin-left: 8px;
            }
        }
    }
}
::v-deep(.ant-form) {
    margin-top: 32px;
}
</style>